package com.memoryangelapplication;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.json.JSONArray;
import org.json.JSONObject;

import com.memoryangelapplication.AlertMessageSinglePreview.ActivitySwipeDetector;
import com.memoryangelapplication.AlertMessageSinglePreview.MyCountDownTimer;
import com.memoryangelapplication.AlertMessageSinglePreview.SoundManager;
import com.memoryangelapplication.services.EventAlarm;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class AlertMessageSinglePreviewM extends Activity   implements OnInitListener, OnUtteranceCompletedListener {
    
	private int MY_DATA_CHECK_CODE = 1;
    private TextToSpeech tts;
    private Handler handler ;
    private SoundManager soundManager;
    private MediaPlayer player;
    
    
    //*************************************************
    String eventTimeStamp;
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
	
	//Display Variables
	String  title;  // Index(3)
	String  description;  // Index(4)
	String  reminder_date;  // Index(6)
	String 	reminder_time; // Index(7)
	String  event_count_flag; 
		
	//Handling Variables
	String  event_id; // Index(0)
	String  event_alam_time; // Index(8)
	String  event_url; // Index(11)
	String  event_package; // Index(12)
	String  event_ack_count; // Index(15)
	String  eventReminderTime; // Index(16)
	String  eventReminderNumber; // Index(17)
	String  eventWaitTime; // Index(18)
	String  eventNotifyType; // Index(19)
	
	//JSONObject eventsListObj = null;
		JSONObject eventsListObjArray = null;
		ArrayList<String> eventsListArray = new ArrayList<String>();
		int TotalEvents = 0;
		RelativeLayout lowestLayout;
		private String eventsMainArray;
		JSONArray jsonarray;
		String updateEventId;
		long nextReminderTimeStamp;
		
		EditText etEventMainId;
		TextView txtViewTitle, txtViewDescription, txtViewReminderDate, txtViewReminderTime, txtViewReminderCount;
		int CurrentPrintIndex = 0;

		ScheduledThreadPoolExecutor executor;
		//ScheduledThreadPoolExecutor executor1;
		/*Handler handler, main_handelr;
		SoundManager soundManager;*/
		//SoundManager1 soundManager1;
		TextToSpeech talker;
		String evtDes;
		//MediaPlayer player;
		//=====================================
		int wait_time = 0;
		int eventwaittimePeriod = 0;
		String DateSendAct, TimeAct, Tzone;
		long TimeStampValue;
		int event_reminder_time = 0;
		int reminder_number = 0;
		int eventTTS = 1;
		int eventContPlay = 1;
		int eventSoundGap = 1000;
		
		String eventURL;
		String eventPackage;
		boolean checkMultipleActive = false;
		
		public static int counter = 0;
		
		final Handler myHandler = new Handler();
	
		private CountDownTimer countDownTimer;
		
		CountDownTimer waitTimer;
		
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.event_values);
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		getWindow().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
		
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);  
		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
		lock.disableKeyguard();

		etEventMainId  = (EditText) findViewById(R.id.eventmainid);
		txtViewTitle  = (TextView) findViewById(R.id.title);
		txtViewDescription  = (TextView) findViewById(R.id.description);
		txtViewReminderDate  = (TextView) findViewById(R.id.reminder_date);
		txtViewReminderTime  = (TextView) findViewById(R.id.reminder_time);
		txtViewReminderCount  = (TextView) findViewById(R.id.eventcounter);
		
		ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
		lowestLayout = (RelativeLayout)this.findViewById(R.id.alert_layout);
		lowestLayout.setOnTouchListener(activitySwipeDetector);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			eventTimeStamp = bundle.getString("eventTimeStamp");
			String CurrentPrintIndexStr = bundle.getString("eventDisplayIDFlag");
			CurrentPrintIndex = Integer.parseInt(CurrentPrintIndexStr);
			
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor fdealerrows = null;
			try {
				String query = "SELECT * FROM table_events WHERE eventTimeStamp = '" + eventTimeStamp + "' AND event_active = '0'";
				fdealerrows = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","1 :" + e);
			}
			if (fdealerrows != null) {
				if (fdealerrows.getCount() > 0) {
					Log.v("Total Count "," : " + fdealerrows.getCount());
					TotalEvents = fdealerrows.getCount();
					int eventIndexCounter = 0;
					while (fdealerrows.moveToNext()) {
						
						Log.v("@@@@@@@@@@@@ "," : " + eventIndexCounter);
						JSONObject eventsListObj = new JSONObject();
						try{
							eventsListObj.put("event_rf_id", eventIndexCounter);
							eventsListObj.put("title", fdealerrows.getString(3));
							eventsListObj.put("description", fdealerrows.getString(4));
							eventsListObj.put("reminder_date", fdealerrows.getString(6));
							eventsListObj.put("reminder_time", fdealerrows.getString(7));
							
							int  eventPrintCount = eventIndexCounter;
							eventPrintCount =  eventPrintCount + 1;
							eventsListObj.put("event_count_flag", eventPrintCount + "  Of  " + TotalEvents + "  Events");
							
							eventsListObj.put("event_id", fdealerrows.getString(1));
							eventsListObj.put("event_alam_time", fdealerrows.getString(8));
							eventsListObj.put("event_url", fdealerrows.getString(11));
							eventsListObj.put("event_package", fdealerrows.getString(12));
							eventsListObj.put("event_ack_count", fdealerrows.getString(15));
							eventsListObj.put("eventReminderTime", fdealerrows.getString(16));
							eventsListObj.put("eventReminderNumber", fdealerrows.getString(17));
							eventsListObj.put("eventWaitTime", fdealerrows.getString(18));
							eventsListObj.put("eventNotifyType", fdealerrows.getString(19));
							eventsListArray.add(eventsListObj.toString());
							eventIndexCounter = eventIndexCounter + 1;
						}
						catch(Exception e){
							Log.v("Print Exception ","2 :" + e);
						}
						
					}
					
					try{
						eventsListObjArray = new JSONObject();
						String EventsArray = eventsListArray.toString();
						eventsListObjArray.put("events", EventsArray);
						
					}
					catch(Exception e){
						Log.v("Print Exception ","3 :" + e);
					}
					//displayEvent();
					
					//************************************************************
					eventsMainArray = eventsListObjArray.toString();
					eventsMainArray = eventsMainArray.replace("\\", "");
					eventsMainArray = eventsMainArray.replace("\"[{", "[{");
					eventsMainArray = eventsMainArray.replace("}]\"}", "}]}");
					
					if(CurrentPrintIndex < 0){
						CurrentPrintIndex = 0;
					}
					String event_id_print = "", title_print = "" , reminder_date_print = "", reminder_time_print = "", event_count_flag_print = "";
					try {
						JSONObject jsonObj = new JSONObject(eventsMainArray);
						jsonarray = jsonObj.getJSONArray("events");
						for (int i = 0; i < jsonarray.length(); i++) {
							JSONObject c = jsonarray.getJSONObject(CurrentPrintIndex);
			            	event_id_print = c.getString("event_id");
			            	title_print = c.getString("title");
			            	evtDes = c.getString("description");
			            	reminder_date_print = c.getString("reminder_date");
			            	reminder_time_print = c.getString("reminder_time");
			            	event_count_flag_print = c.getString("event_count_flag");
			            	
			            	updateEventId = c.getString("event_alam_time");
			            	
			            	etEventMainId.setText(event_id_print);
			            	txtViewTitle.setText(title_print);
			            	txtViewDescription.setText(evtDes);
			            	txtViewReminderDate.setText(reminder_date_print);
			            	txtViewReminderTime.setText(reminder_time_print);
			            	txtViewReminderCount.setText(event_count_flag_print);
			            	
			            	
			            	String StrEventWaitTime = c.getString("eventWaitTime");
			    			eventwaittimePeriod = Integer.parseInt(StrEventWaitTime);
			    			wait_time = eventwaittimePeriod * 1000;
			    			//***************************************************
			    			String StreventReminderTime = c.getString("eventReminderTime");
			    			event_reminder_time = Integer.parseInt(StreventReminderTime);
			    			//***************************************************
			    			String StreventReminderNumber = c.getString("eventReminderNumber");
			    			reminder_number = Integer.parseInt(StreventReminderNumber);
			    		
			    			//***************************************************
			    			
			    			if (reminder_number == 0) {
		    					reminder_number = 3;

		    				}
		    				// Reminder Delay
		    				if (event_reminder_time == 0) {
		    					event_reminder_time = 60;

		    				}
		    				// Display Reminder
		    				if (wait_time == 0) {
		    					// if 0 then default will be 5
		    					wait_time = 45 * 1000;
		    				}
		    				eventTTS = 1;
		    				eventContPlay = 1;
		    				eventSoundGap = 1000;

		    				if (eventSoundGap == 0) {
		    					eventSoundGap = 5;
		    				}
		    				
		    				//***************************************************
			    			// Time Zone Of the Current Phone
			    			Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
			    			Date currentLocalTime = calendar.getTime();
			    			DateFormat date = new SimpleDateFormat("Z");
			    			Tzone = date.format(currentLocalTime);
			    			Tzone = " " + Tzone;
			    			String currentTime = getAddDateTimeStringPreCheck();
			    			String[] CheckDayTime = currentTime.split(" ");
			    			DateSendAct = CheckDayTime[0];
			    			TimeAct = CheckDayTime[1];
			    			getNativeTimeStamp(DateSendAct, TimeAct, Tzone);
						}
					}
					catch(Exception e){
						Log.v("Print Exception ","5 :" + e);
					}
					
					//*************************************************************
					//printFirstRecord();
				}
			}
		}
		
		soundManager = new SoundManager();
		handler = new Handler();
		handler.postDelayed(soundManager, 1000);
         //check for the presence of the TTS resources with the corresponding intent 
		tts = new TextToSpeech(this, this);
		
		try {
			Vibrator myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
			myVib.vibrate(1500);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		 
	/*	countDownTimer = new MyCountDownTimer(wait_time, 1000);
		countDownTimer.start();*/
		
		 waitTimer = new CountDownTimer(wait_time, 1000) {

		       public void onTick(long millisUntilFinished) {
		          //called every 300 milliseconds, which could be used to
		          //send messages or some other action
		    	   Log.e("Timmer ", " : " + millisUntilFinished / 1000 + "/" + wait_time);
		       }

		       public void onFinish() {
		          //After 60000 milliseconds (60 sec) finish current 
		          //if you would like to execute something when time finishes   
			    	 if(TotalEvents > 1){
			    		 eventDetailsUpdate();
			    		 CurrentPrintIndex = CurrentPrintIndex + 1;
							if(CurrentPrintIndex == TotalEvents){
								//onRightToLeftSwipe();
							}
							if(CurrentPrintIndex > TotalEvents){
								CurrentPrintIndex = CurrentPrintIndex - 2;
								if(waitTimer != null) {
							         waitTimer.cancel();
							         waitTimer = null;
							     }
								readNextEventSchedule();
							}
							else{
								if(waitTimer != null) {
							         waitTimer.cancel();
							         waitTimer = null;
							     }
								readNextEventSchedule();
							}
			    	 }
			    	 
			    	 else{
			    		if(waitTimer != null) {
			    	         waitTimer.cancel();
			    	         waitTimer = null;
			    	    }
			    		eventDetailsUpdate();
						setNextReminder();
						AlertMessageSinglePreviewM.this.finish();
			    	 }
		       }
		     }.start();

/*		new CountDownTimer(wait_time, 1000) {

		     public void onTick(long millisUntilFinished) {
		    	 Log.e("Timmer Started", " : " + millisUntilFinished / 1000);
		     }

		     public void onFinish() {
		    	 if(TotalEvents > 1){
		    		 eventDetailsUpdate();
		    		 CurrentPrintIndex = CurrentPrintIndex + 1;
						if(CurrentPrintIndex == TotalEvents){
							//onRightToLeftSwipe();
						}
						if(CurrentPrintIndex > TotalEvents){
							CurrentPrintIndex = CurrentPrintIndex - 2;
							readNextEventSchedule();
						}
						else{
							readNextEventSchedule();
						}
		    	 }
		    	 
		    	 else{
		    		eventDetailsUpdate();
					setNextReminder();
					AlertMessageSinglePreviewM.this.finish();
		    	 }
		     }
		 }.start();*/
		 	lowestLayout.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					 if(TotalEvents > 1){
					    	
							//countDownTimer.cancel();
							if (tts  != null) {
						        tts.shutdown();
						    }
						    if (soundManager  != null) {
						        handler.removeCallbacks(soundManager);
						    }
						    if(waitTimer != null) {
						         waitTimer.cancel();
						         waitTimer = null;
						     }
						    
					    	checkMultipleActive = true;
					    	Log.v("Print ", "onTopToBottomSwipe : " + checkMultipleActive);
					    	eventsMainArray = "";
					    	eventsListObjArray = new JSONObject();
					    	eventsListArray.clear();
					    	updateState();
					    }
					    else{
					    	
							//countDownTimer.cancel();
							if (tts  != null) {
						        tts.shutdown();
						    }
						    if (soundManager  != null) {
						        handler.removeCallbacks(soundManager);
						    }
						    if(waitTimer != null) {
						         waitTimer.cancel();
						         waitTimer = null;
						     }
						    
					    	updateState();
					    }
					return false;
				}
				
			});
	}
	
	
	//***********************************************************
	
	public class MyCountDownTimer extends CountDownTimer {
		public MyCountDownTimer(long startTime, long interval) {
			super(startTime, interval);
		}

		@Override
		public void onFinish() {
			 if(TotalEvents > 1){
	    		 eventDetailsUpdate();
	    		 CurrentPrintIndex = CurrentPrintIndex + 1;
					if(CurrentPrintIndex == TotalEvents){
						//onRightToLeftSwipe();
					}
					if(CurrentPrintIndex > TotalEvents){
						CurrentPrintIndex = CurrentPrintIndex - 2;
						readNextEventSchedule();
					}
					else{
						readNextEventSchedule();
					}
	    	 }
			 else{
		    		eventDetailsUpdate();
					setNextReminder();
					AlertMessageSinglePreviewM.this.finish();
		    	 }
		}

		@Override
		public void onTick(long millisUntilFinished) {
			Log.v("Log ", "Timmer : " + millisUntilFinished / 1000);
			//text.setText("" + millisUntilFinished / 1000);
		}
	}
	
	//***********************************************************
	
	protected void setNextReminder() {
		try{
			Bundle bundle = new Bundle();
			EventAlarm alarm1 = new EventAlarm(getBaseContext(), bundle, event_reminder_time);
		}
		catch(Exception e){
			Log.v("Print Exception ","8 :" + e);
		}
		
	}
	
	//***********************************************************
	
	protected void readNextEventSchedule() {
		// TODO Auto-generated method stub
		Log.v("<<<<<<","Moving Multiple>>>>>>");
		countDownTimer.cancel();
		Intent intentDirectLog = new Intent(getBaseContext(),
				AlertMessageSinglePreview.class);
		intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
		intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
		intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intentDirectLog);
		finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}

	//***********************************************************
	
	protected void eventDetailsUpdate() {
		Log.v(">>>>>>>>>>>>>>>>> ","Event Details Update");
		// TODO Auto-generated method stub
		String UpdatedEvent = etEventMainId.getText().toString();
		Log.v("Print ", "updateEventId : " + UpdatedEvent);
		mydb = openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		Cursor checkPreEventsAckCount = null;

		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_log_id = '" + UpdatedEvent + "'";
			checkPreEventsAckCount = mydb.rawQuery(query, null);
		} catch (Exception e) {
			Log.v("Print Exception ","7 :" + e);
		}
		if (checkPreEventsAckCount != null) {
			if (checkPreEventsAckCount.getCount() > 0) {
				while (checkPreEventsAckCount.moveToNext()) {
					ContentValues updateEvetsCount = new ContentValues();
					String updateID = checkPreEventsAckCount.getString(0);
					String event_alam_time = checkPreEventsAckCount.getString(2);
					long event_alam_timecount = Long.parseLong(event_alam_time);
					String updateCounter = checkPreEventsAckCount.getString(3);
					String eventReminderTime = checkPreEventsAckCount.getString(4);
					String eventReminderNumber = checkPreEventsAckCount.getString(5);
					String eventWaitTime = checkPreEventsAckCount.getString(6);
					String eventCurrentTimeStamp = checkPreEventsAckCount.getString(7);

					int eventReminderNumbercount = Integer.parseInt(eventReminderNumber);
					// Event Reminder Time = Time 1
					long eventReminderTimecount = Long.parseLong(eventReminderTime);
					long eventeventWaitTimecount = Long.parseLong(eventWaitTime);
					long eventeventCurrentTimeStamp = Long.parseLong(eventCurrentTimeStamp);

					Log.v("","Reminder Time Count****: " + eventReminderTimecount);
					Log.v("","Wait Time Count********: " + eventeventWaitTimecount);
					
					long curCount = Long.parseLong(updateCounter);
					curCount = curCount + 1;

					long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount) * curCount;
					newEventCurrentTimeStamp = newEventCurrentTimeStamp + TimeStampValue;
					String newEventCurrentTimeStampStr = String.valueOf(newEventCurrentTimeStamp);
					
					Log.v("","Current Time Stamp*****: " + newEventCurrentTimeStampStr);

					if (eventReminderNumbercount == curCount) {
						updateEvetsCount.put("event_status", "4");
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_active", "1");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
					} else {
						nextReminderTimeStamp = newEventCurrentTimeStamp;
						newEventCurrentTimeStampStr = String.valueOf(nextReminderTimeStamp);
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_status", "9");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount, "event_log_id ='" + updateID + "'", null);
					}

				}
			}
		}
		checkPreEventsAckCount.close();
		mydb.close();
		//printFirstRecord();  
		CurrentPrintIndex = 0;
	}
	

	//***********************************************************
	
	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	//***********************************************************
	
	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;
		try {
			d = ddMMMyyFormat.parse(DateSend.trim() + " " + Time.trim() + Tzone);
		} catch (ParseException e) {
			Log.v("Print Exception ","6 :" + e);
		}

		c.setTime(d);

		@SuppressWarnings("unused")
		String date_to_string = ddMMMyyFormat.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}
	
	//***********************************************************
	
	// A successful check will be marked by a CHECK_VOICE_DATA_PASS result code,
    // indicating this device is ready to speak, after the creation of our TextToSpeech object.
    // If not, we need to let the user know to install the data that's required for the device
    // to become a multi-lingual talking machine! Downloading and installing the data is
    // accomplished by firing off the ACTION_INSTALL_TTS_DATA intent, which will take the
    // user to Android Market, and will let her/him initiate the download. Installation of
    // the data will happen automatically once the download completes. Here is an example
    // of what your implementation of onActivityResult()
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MY_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // Success, create the TTS instance
                tts = new TextToSpeech(this, this);
            }
            else {
                // TextToSpeech data is missing, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

   //***********************************************************
    
    /*speak() calls are asynchronous, so they will return well before the text is done
     * being synthesized and played by Android, regardless of the use of QUEUE_FLUSH or QUEUE_ADD.
     * But you might need to know when a particular utterance is done playing. We also need to make
     * sure our activity implements the TextToSpeech.OnUtteranceCompletedListener interface
     */
    @Override
    public void onUtteranceCompleted(String uttId) {
        Log.v("AndroidTextToSpeechActivity", uttId);
        if (uttId.equalsIgnoreCase("done")) {
            Log.v("AndroidTextToSpeechActivity", "Done talking, end of message");
            handler.postDelayed(soundManager, 1000);
        }
    }
    
	//***********************************************************

	 @Override
	    public void onInit(int status) {      
	        if (status == TextToSpeech.SUCCESS) {
	            //Toast.makeText(this,"Text-To-Speech engine is Ready", Toast.LENGTH_SHORT).show();
	            //Set language
	            tts.setLanguage(Locale.US);
	            // Set listener to know when a particular utterance is done playing
	            int result = tts.setOnUtteranceCompletedListener(this);
	            Log.v("AndroidTextToSpeechActivity", "Result: " + result);
	        }
	        else if (status == TextToSpeech.ERROR) {
	            Toast.makeText(this,"Error initializing Text-To-Speech engine", Toast.LENGTH_SHORT).show();
	        }
	    }
	 
	//***********************************************************
	 
	 @Override
	    protected void onDestroy() {
	        Log.v("AndroidTextToSpeechActivity", "onDestory");
	        super.onDestroy();
	        if (tts  != null) {
	            tts.shutdown();
	        }
	        if (soundManager  != null) {
	        handler.removeCallbacks(soundManager);
	        }
	        
	        if(waitTimer != null) {
		         waitTimer.cancel();
		         waitTimer = null;
		     }
	    }

	//***********************************************************
	 
	  @Override
	    protected void onStop() {
	        super.onStop();
	        Log.v("AndroidTextToSpeechActivity", "onStop");
	        if (tts  != null) {
	            tts.shutdown();
	        }
	        if (soundManager  != null) {
	        handler.removeCallbacks(soundManager);
	        }
	    }
	  
	//***********************************************************
	  
	    class SoundManager implements Runnable {

	        @Override
	        public void run() {

	            setVolumeControlStream(AudioManager.STREAM_MUSIC);
	            // our file here is in fact called "soundfile.mp3";

	            player = MediaPlayer.create(
	            		AlertMessageSinglePreviewM.this, R.raw.alarm);
	            // we start playing the file!
	            player.start();

	            player.setOnCompletionListener(new OnCompletionListener() {

	                @Override
	                public void onCompletion(MediaPlayer mp) {
	                    mp.stop();
	                    mp.release();
	                   
	                   //String inputText = txtViewDescription.getText().toString();
	                   String inputText = evtDes;
	                    if (inputText!=null && inputText.length()>0) {
	                        //for(int i=0;i<3;i++){
	                            tts.speak(inputText, TextToSpeech.QUEUE_FLUSH, null);
	                        //}
	                           
	                        // Set utteranceId to know when a particular utterance is done playing
	                        HashMap<String, String> myHash = new HashMap<String, String>();
	                        myHash.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"done");
	                        tts.speak(".", TextToSpeech.QUEUE_ADD, myHash);
	                       
	                        //handler.postDelayed(soundManager, 1000);
	                    }
	                   
	                }
	            });
	           
	            //handler.postDelayed(this, 3000);
	           
	        }

	    }
	    
	    
	    
	  //======================================================================
		
		public class ActivitySwipeDetector implements View.OnTouchListener {

			static final String logTag = "ActivitySwipeDetector";
			@SuppressWarnings("unused")
			private Activity activity;
			static final int MIN_DISTANCE = 100;
			private float downX, downY, upX, upY;

			public ActivitySwipeDetector(Activity activity){
			    this.activity = activity;
			}

			public void onRightToLeftSwipe(){
			    if(CurrentPrintIndex <= TotalEvents && TotalEvents > 1){
			    	
			    		//countDownTimer.cancel();
			    	  	if (tts  != null) {
				            tts.shutdown();
				        }
				        if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				        }
				        
				        if(waitTimer != null) {
					         waitTimer.cancel();
					         waitTimer = null;
					     }
				        
			    	    CurrentPrintIndex = CurrentPrintIndex + 1;
			    	    Log.v("CurrentPrintIndex ", " RightToLeftSwipe : " + CurrentPrintIndex);
						Intent intentDirectLog = new Intent(getBaseContext(),
								AlertMessageSinglePreview.class);
						intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
						intentDirectLog.putExtra("eventDisplayIDFlag",   "" + CurrentPrintIndex);
						intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intentDirectLog);
						finish();
						overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			    }
			}
			
			public void onLeftToRightSwipe(){
				if(CurrentPrintIndex > 0 && TotalEvents > 1){
					
					//countDownTimer.cancel();
					if (tts  != null) {
				        tts.shutdown();
				    }
				    if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				    }
				    
				    if(waitTimer != null) {
				         waitTimer.cancel();
				         waitTimer = null;
				     }
				    
			    	CurrentPrintIndex = CurrentPrintIndex - 1;
			    	Log.v("CurrentPrintIndex ", " onLeftToRightSwipe : " + CurrentPrintIndex);
			    	Intent intentDirectLog = new Intent(getBaseContext(),
							AlertMessageSinglePreview.class);
					intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
					intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intentDirectLog);
					finish();
					overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
				}
			}
			
			public void onTopToBottomSwipe(){
			    if(TotalEvents > 1){
			    	
					//countDownTimer.cancel();
					if (tts  != null) {
				        tts.shutdown();
				    }
				    if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				    }
				    if(waitTimer != null) {
				         waitTimer.cancel();
				         waitTimer = null;
				     }
				    
			    	checkMultipleActive = true;
			    	Log.v("Print ", "onTopToBottomSwipe : " + checkMultipleActive);
			    	eventsMainArray = "";
			    	eventsListObjArray = new JSONObject();
			    	eventsListArray.clear();
			    	updateState();
			    }
			    else{
			    	
					//countDownTimer.cancel();
					if (tts  != null) {
				        tts.shutdown();
				    }
				    if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				    }
				    if(waitTimer != null) {
				         waitTimer.cancel();
				         waitTimer = null;
				     }
				    
			    	updateState();
			    }
			}
			
			
			public void onBottomToTopSwipe(){
			    if(TotalEvents > 1){
			    	
					//countDownTimer.cancel();
					if (tts  != null) {
				        tts.shutdown();
				    }
				    if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				    }
				    if(waitTimer != null) {
				         waitTimer.cancel();
				         waitTimer = null;
				     }
				    
			    	checkMultipleActive = true;
			    	Log.v("Print ", "onTopToBottomSwipe : " + checkMultipleActive);
			    	eventsMainArray = "";
			    	eventsListObjArray = new JSONObject();
			    	eventsListArray.clear();
			    	updateState();
			    }
			    else{
					//countDownTimer.cancel();
					if (tts  != null) {
				        tts.shutdown();
				    }
				    if (soundManager  != null) {
				        handler.removeCallbacks(soundManager);
				    }
				    if(waitTimer != null) {
				         waitTimer.cancel();
				         waitTimer = null;
				     }
				    
			    	updateState();
			    }
			}

			@Override
			public boolean onTouch(View v, MotionEvent event) {
			    switch(event.getAction()){
			     
			        case MotionEvent.ACTION_DOWN: {
			            downX = event.getX();
			            downY = event.getY();
			            return true;
			        }
			        case MotionEvent.ACTION_UP: {
			            upX = event.getX();
			            upY = event.getY();

			            float deltaX = downX - upX;
			            float deltaY = downY - upY;

			       // swipe horizontal?
			        if(Math.abs(deltaX) > Math.abs(deltaY))
			        {
			            if(Math.abs(deltaX) > MIN_DISTANCE){
			                // left or right
			                if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
			                if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
			            }
			            else {
			                    Log.i(logTag, "Horizontal Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
			                    return false; // We don't consume the event
			            }
			        }
			        // swipe vertical?
			        else 
			        {
			            if(Math.abs(deltaY) > MIN_DISTANCE){
			                // top or down
			                if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
			                if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
			            }
			            else {
			                    Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
			                    return false; // We don't consume the event
			            }
			        }

			            return true;
			        }
			    }
			    return false;
			}		
		}

		//*******************Update Acknoledge States******************

		protected void updateState() {
			// TODO Auto-generated method stub
			String UpdatedEvent = etEventMainId.getText().toString();
			Log.v("Print ", "updateEventId : " + UpdatedEvent);
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor checkPreEvents = null;
			try {
				String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_url,event_package FROM table_events Where event_log_id = '" + UpdatedEvent + "'";
				checkPreEvents = mydb.rawQuery(query, null);
			} catch (Exception e) {
				Log.v("Print Exception ","9 :" + e);
			}
			if (checkPreEvents != null) {
				if (checkPreEvents.getCount() > 0) {
					while (checkPreEvents.moveToNext()) {
						Log.v("******@@@@@@@","******");
						ContentValues updateEvets = new ContentValues();
						String updateID = checkPreEvents.getString(0);
						eventURL = checkPreEvents.getString(3);
						eventPackage = checkPreEvents.getString(4);

						updateEvets.put("event_status", "3");
						updateEvets.put("event_active", "1");
						updateEvets.put("event_update_time", getAddDateTimeString().toString());
						mydb.update(MEM_EVENT, updateEvets, "event_log_id ='" + UpdatedEvent + "'", null);
					}
				}
			}
			checkPreEvents.close();
			mydb.close();
			
			Log.e("REQUEST 1:", "VAL PASS 1 :" +eventURL);
			Log.e("REQUEST 2:", "VAL PASS 2 :" +eventPackage);
			
			if (eventPackage.equals("404") && eventURL.equals("404")) {
				//closeExcecutor();
				/*AlertMessageSinglePreview.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());*/
				if(checkMultipleActive = true){
					if(TotalEvents > 1){
						CurrentPrintIndex = 0;
						reloadEvents();
					}
					else{
						//closeExcecutor();
						AlertMessageSinglePreviewM.this.finish();
						finish();
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}
			} else if (!eventURL.equals("404")) {
				try {
					Log.e("REQUEST :", "Fire URL**********");
					//closeExcecutor();
					Intent viewIntent = new Intent("android.intent.action.VIEW",
							Uri.parse(eventURL.trim()));
					viewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
	                         | Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(viewIntent);
					AlertMessageSinglePreviewM.this.finish();
					finish();
					android.os.Process.killProcess(android.os.Process.myPid());
				} catch (Exception e) {
					Log.v("Print Exception ","10 :" + e);
				}
			} else if (!eventPackage.equals("404")) {
				Log.e("REQUEST :", "Fire Package************");
				//closeExcecutor();
				Intent i = new Intent(Intent.ACTION_MAIN);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
	                    | Intent.FLAG_ACTIVITY_NEW_TASK);
				PackageManager managerclock = getPackageManager();
				i = managerclock.getLaunchIntentForPackage(eventPackage.trim());
				i.addCategory(Intent.CATEGORY_LAUNCHER);
				startActivity(i);
				AlertMessageSinglePreviewM.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			}
			else{
				if(checkMultipleActive = true){
					if(TotalEvents > 1){
						CurrentPrintIndex = 0;
						reloadEvents();
					}
					else{
						AlertMessageSinglePreviewM.this.finish();
						finish();
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}
			}
			/*
			 * //Allow To Trigger If Previous Events Excisting Bundle bundle = new
			 * Bundle(); EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
			 */
		}
		
		private String getAddDateTimeString() {
			Calendar cad = Calendar.getInstance();
			SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String formattedAddDate = dfad.format(cad.getTime());
			return formattedAddDate;
		}
		
		private void reloadEvents() {
			// TODO Auto-generated method stub
			Intent intentDirectLog = new Intent(getBaseContext(),
					AlertMessageSinglePreview.class);
			intentDirectLog.putExtra("eventTimeStamp", eventTimeStamp);
			intentDirectLog.putExtra("eventDisplayIDFlag", "" + CurrentPrintIndex);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentDirectLog);
			this.finish();
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		}
}
